package com.lsz.custom;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.kymjs.kjframe.KJHttp;
import org.kymjs.kjframe.http.HttpCallBack;

import java.io.File;

/**
 * Created by leishize on 2016/8/28.
 */
public class MateDownLoad extends CordovaPlugin {

  private Context ctx;

  private KJHttp fh;

  private CallbackContext callback;

  private String url;

  @Override
  public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    ctx = cordova.getActivity();
    fh = new KJHttp();
    url = args.getString(0);
    callback = callbackContext;
    if (Build.VERSION.SDK_INT >= 23) {
      int checkPermission = ContextCompat.checkSelfPermission(cordova.getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
      if (checkPermission != PackageManager.PERMISSION_GRANTED) {
        if (!cordova.getActivity().getPreferences(Context.MODE_PRIVATE).getBoolean("isFirst", true)) {
          if (!ActivityCompat.shouldShowRequestPermissionRationale(cordova.getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            callback.error("应用没有访问存储空间的权限,请到设置->应用里进行权限设置或使用浏览器下载");
          }
        }else{
          cordova.getActivity().getPreferences(Context.MODE_PRIVATE).edit().putBoolean("isFirst", true).commit();
        }
        cordova.requestPermissions(this,2, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE});
      } else {
        cordova.getActivity().runOnUiThread(new Runnable() {
          @Override
          public void run() {
            down(url);
          }
        });
      }
    }else{
      cordova.getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
          down(url);
        }
      });
    }
    return true;
  }

  ProgressDialog progressDialog = null;

  @Override
  public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) throws JSONException {
    if (requestCode == 2) {
      if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        down(url);
      }else{
        callback.error("应用没有访问存储空间的权限,请到设置->应用里进行权限设置或<b>使用浏览器下载</b>");
      }
    }
    super.onRequestPermissionResult(requestCode, permissions, grantResults);
  }

  public void down(String url) {
    progressDialog = new ProgressDialog(ctx);
    progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    progressDialog.setIndeterminate(false);
    progressDialog.setCancelable(false);
    progressDialog.show();
    final String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/DTDownLoad/client.apk";

    String dist = Environment.getExternalStorageDirectory().getAbsolutePath() + "/DTDownLoad";

    File fdist = new File(dist);

    if(fdist.exists()){
      deleteAllFilesOfDir(fdist);
    }

    if(!fdist.exists()){
      fdist.mkdir();
    }
    //删除上次下载的文件
//    File downFile = new File(path);
//    if (downFile.exists()) {
//      downFile.delete();
//    }

    fh.download(path, url, new HttpCallBack() {
      @Override
      public void onFailure(int errorNo, String strMsg) {
        progressDialog.dismiss();
        callback.error("下载失败,请检查网络是否连接");
      }

      @Override
      public void onSuccess(byte[] t) {
        progressDialog.dismiss();
        setup(new File(path));
      }

      @Override
      public void onLoading(long count, long current) {
        progressDialog.setMax((int) count);
        progressDialog.setProgress((int) current);
        progressDialog.setMessage(current + "/" + count);
        System.out.println(count + "/" + current);
      }
    });
  }

  @Override
  public void onDestroy() {
    fh.cancelAll();
    super.onDestroy();
  }

  private void setup(File file) {
    int result = Settings.Secure.getInt(ctx.getContentResolver(),
      Settings.Secure.INSTALL_NON_MARKET_APPS, 0);
    Intent it = new Intent(Intent.ACTION_VIEW);
    it.setDataAndType(Uri.fromFile(file),
      "application/vnd.android.package-archive");
    ctx.startActivity(it);
    System.exit(0);
  }

  public static void deleteAllFilesOfDir(File path) {
    if (!path.exists())
      return;
    if (path.isFile()) {
      path.delete();
      return;
    }
    File[] files = path.listFiles();
    for (int i = 0; i < files.length; i++) {
      deleteAllFilesOfDir(files[i]);
    }
    path.delete();
  }


}
